<template>
  <el-dialog :title="t('keys.joinTheCompany')" v-model="dialogVisible" width="1000px" :close-on-click-modal="false">
    <div class="contract_base_title">企业信息</div>
    <el-form ref="formSearchRef" label-position="top" :model="ruleForm" :rules="rules" label-width="120px">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item :label="t('keys.Enterprise_name')" prop="companyName">
            <el-select
              v-model.trim="ruleForm.companyName"
              filterable
              remote
              style="width: 100%"
              reserve-keyword
              :placeholder="t('keys.Please_name_search')"
              remote-show-suffix
              :remote-method="remoteMethod"
              @change="changeCompany"
              :loading-text="t('keys.loadingInThe')"
              :no-data-text="t('keys.noData')"
              @blur="selectBlur"
            >
              <el-option v-for="item in companyOptions" :key="item.companyName" :label="item.companyName" :value="item.companyName" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('keys.unique_code')" prop="creditCode">
            <el-input v-model.trim="ruleForm.creditCode" :placeholder="t('keys.pleaseEnter')" disabled clearable maxlength="22"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="contract_base_title">{{ t('keys.Request_User_Information') }}</div>
    <base-form
      ref="formRef"
      v-model="ruleForm"
      :schema="formList"
      :rules="rules"
      :options="{ span: 12, labelPosition: 'top', type: 'form', labelWidth: 120 }"
      @change="_change"
    >
    </base-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ t('keys.cancel') }}</el-button>
        <el-button type="primary" :loading="loading" @click="handelSubmit()">{{ t('keys.ok') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { validatePhone, validateEmail, validateUppercase18, validateNum9 } from 'src/utils/validate'
import { getCompanySearchApi, postRegisterCompanyApi, sceneDetail } from 'api/common'
import { ERR_OK } from 'config/statusCode'

const { t } = useI18n() // 中英文
const emit = defineEmits(['refresh'])
const dialogVisible = ref(false)
const formRef = ref(null)
const formSearchRef = ref(null)
const userInfo = ref()
const formList = ref([
  {
    label: t('keys.full_name'),
    field: 'realName',
    component: 'Input',
    componentProps: {
      disabled: true
    }
  },
  {
    label: t('keys.address_tel'),
    field: 'phone',
    component: 'Input',
    componentProps: {
      disabled: true
    }
  },
  {
    label: t('keys.Mailbox'),
    field: 'email',
    component: 'Input',
    componentProps: {
      disabled: true
    }
  },
  // {
  //   label: t('keys.fileUid'),
  //   field: 'file',
  //   component: 'FileUpload',
  //   desc: t('keys.Please_file_tips'),
  //   componentProps: {
  //     fieldSceneVo: {
  //       moduleCode: 'emd',
  //       sceneCode: 'picture_single_1',
  //       fieldTypeCode: 'file',
  //     },
  //     limit:'1',
  //     upType: 'file'
  //   }
  // },
  {
    label: t('keys.remark'),
    field: 'remark',
    component: 'Input',
    placement: 'bottom',
    componentProps: {
      type: 'textarea',
      maxlength: '200',
      showWordLimit: true
    }
  }
])
const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.phone_cant_empty')))
  }
  setTimeout(() => {
    if (!Number.isInteger(+value)) {
      callback(new Error(t('keys.please_enter_number_tips')))
    } else {
      if (validatePhone(value)) {
        callback()
      } else {
        callback(new Error(t('keys.reg_tele_empty_format_tips')))
      }
    }
  }, 100)
}

const checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t('keys.email_cant_empty')))
  }
  setTimeout(() => {
    if (validateEmail(value)) {
      callback()
    } else {
      callback(new Error(t('keys.Email_format_error')))
    }
  }, 100)
}

const ruleForm = ref({
  realName: '',
  email: '',
  phone: '',
  file: '',
  fileList: [],
  remark: '',

  action: 'APPLY_MEMBER',
  companyName: '',
  creditType: 'DOMESTIC_ENTERPRISES',
  creditCode: ''
})
const rules = reactive({
  realName: [{ required: true, message: t('keys.name_empty'), trigger: ['blur', 'change'] }],
  phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
  email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
  companyName: [{ required: true, message: t('keys.Enterprise_name_format_tips'), trigger: ['blur', 'change'] }],
  creditCode: [{ required: true, message: t('keys.Social_credit_vis_code_format_tips'), trigger: ['blur', 'change'] }]
})

const errorTips = ref({
  realName: '',
  email: '',
  phone: '',
  file: '',
  fileList: [],
  remark: '',

  action: 'APPLY_MEMBER',
  companyName: '',
  creditType: 'DOMESTIC_ENTERPRISES',
  creditCode: ''
})

const initErrorTips = () => {
  for (var key in errorTips.value) {
    errorTips.value[key] = ''
  }
}

const _change = (val) => {}

const showDialog = (data) => {
  userInfo.value = JSON.parse(localStorage.getItem('userinfo')) || {}
  if (userInfo.value?.userType == 'DOMESTIC') {
    formList.value = formList.value.filter((item) => item.field != 'email')
  } else {
    formList.value = formList.value.filter((item) => item.field != 'phone')
  }
  ruleForm.value.realName = userInfo.value?.realName || ''
  ruleForm.value.phone = userInfo.value?.userPhone || ''
  ruleForm.value.email = userInfo.value?.userEmail || ''
  ruleForm.value.fileList = []
  dialogVisible.value = true
  formSearchRef.value?.resetFields()
  formRef.value?.resetFields()
}
// 站内企业查询
const companyOptions = ref([])
const remoteMethod = async (query) => {
  if (query) {
    const res = await getCompanySearchApi({ keywords: query, type: 'local' })
    if (res.code == ERR_OK) {
      companyOptions.value = res.data || []
    }
  } else {
    companyOptions.value = []
  }
}
const changeCompany = (val) => {
  const item = companyOptions.value.find((item) => item.companyName === val) || {}
  ruleForm.value.creditCode = item?.creditCode || ''
  ruleForm.value.creditType = item?.creditType || ''
}
const selectBlur = (e) => {
  nextTick(() => {
    ruleForm.value.companyName = e.target.value
  })
}

onMounted(() => {})
const loading = ref(false)
// 提交
const handelSubmit = async (pwdFormRef) => {
  if (loading.value) return
  initErrorTips()
  let valid = await formSearchRef.value.validate().catch((res) => {
    return false
  })
  if (!valid) return
  let seraValid = await formRef.value.validate().catch((res) => {
    return false
  })
  if (!seraValid) return
  if (valid && seraValid) {
    loading.value = true
    const compyRes = await postRegisterCompanyApi(ruleForm.value)
    if (compyRes.code === ERR_OK) {
      dialogVisible.value = false
      ElMessage.success(t('keys.operation_succeeded'))
      emit('refresh')
      setTimeout(() => {
        loading.value = false
      }, 1000)
    } else {
      dialogVisible.value = false
      setTimeout(() => {
        loading.value = false
      }, 1000)
    }
  }
}
defineExpose({
  showDialog
})
</script>
